package com.lp.multi.thread.example05;

/**
 * @author: lp
 * @create: 2021-06-22 10:44
 * @description: 并发不安全案例1，并发买票
 */
public class UnSafeBuyTicketThreadTest {
    public static void main(String[] args) {
        SellTicketThread sellTicketThread = new SellTicketThread();
        new Thread(sellTicketThread,"普通用户").start();
        new Thread(sellTicketThread,"黄牛").start();
        new Thread(sellTicketThread,"苦逼的我").start();

    }
}

class SellTicketThread implements Runnable{
    /**
     * 线程停止标志
     */
    private boolean flag=true;
    /**
     * 票的数量
     */
    private int ticketNum =10;

    @Override
    public void run() {
        while(flag){
            try {
                buyTicket();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buyTicket() throws InterruptedException {
        if(ticketNum <= 0){
            System.out.println(Thread.currentThread().getName()+"买票失败:"+ticketNum);
            stop();
            return ;
        }
        Thread.sleep(10);
        System.out.println(Thread.currentThread().getName()+"买票成功:"+ticketNum--);
    }

    private boolean stop(){
        this.flag =false;
        return true;
    }
}
